package cn.xiaopengstack.trigger.http;

import cn.xiaopengstack.api.service.ILoginService;
import cn.xiaopengstack.response.Response;
import cn.xiaopengstack.types.enums.ResponseCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @author jiangyangang
 */
@RestController
@Slf4j
@CrossOrigin("*")
@RequestMapping("/api/v1/login/")
public class LoginController {

    @Resource
    private ILoginService loginService;

    /**
     * 获取微信二维码
     * @return
     */
    @RequestMapping(value = "weixin_qrcode_ticket", method = RequestMethod.GET)
    public Response<String> weixinQrcodeTicket() {
        // 登录
        String qrCodeTicket = null;
        try {
            qrCodeTicket = loginService.createQrCodeTicket();
            log.info("生成微信扫码登录 ticket:{}", qrCodeTicket);
            return Response.<String>builder()
                    .data(qrCodeTicket)
                    .code(ResponseCode.SUCCESS.getCode())
                    .info(ResponseCode.SUCCESS.getInfo())
                    .build();
        } catch (IOException e) {
            return Response.<String>builder()
                    .data(qrCodeTicket)
                    .code(ResponseCode.UN_ERROR.getCode())
                    .info(ResponseCode.UN_ERROR.getInfo())
                    .build();
        }

    }


    /**
     * 检查登录
     * @param ticket
     * @return
     */
    @RequestMapping(value = "weixin_check_login", method = RequestMethod.GET)
    public Response<String> weixinCheckLogin(@RequestParam String ticket) {
        String token = loginService.checkLogin(ticket);
        if (StringUtils.isNotBlank(token)) {
            return Response.<String>builder()
                    .data(token)
                    .code(ResponseCode.SUCCESS.getCode())
                    .info(ResponseCode.SUCCESS.getInfo())
                    .build();
        } else {
            return Response.<String>builder()
                    .data(token)
                    .code(ResponseCode.NOT_LOGIN.getCode())
                    .info(ResponseCode.NOT_LOGIN.getInfo())
                    .build();
        }


    }
}
